﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Model;
using System.Text;
using System.Configuration;
using System.Web.Script.Serialization;
using Model.ModelForJD;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
using Model.EntityModel;
using IData;

/// <summary>
/// JDUtil 的摘要说明
/// </summary>
public class JDUtil
{
    private static readonly JDUtil Instance = new JDUtil();

    private static string strPath = HttpContext.Current.Server.MapPath("~") + "\\ErrorLog\\";

    private static JavaScriptSerializer jss = new JavaScriptSerializer();

    private JDUtil()
    {

    }

    public static JDUtil GetInstance
    {
        get { return Instance; }
    }

    /// <summary>
    /// 获取京东Token码接口
    /// </summary>
    /// <returns></returns>
    public static TokenForJD GetJdToken()
    {
        //获取京东Token码
        TokenForJD tokenmodel = JsonConvert.DeserializeObject<TokenForJD>(DataInteractForJD.GetJdToken());
        return tokenmodel;
    }

    public bool SubmitOrderForJD(Shop_Order shopOrder)
    {
        SubmitOrderParamForJD submitOrderParamForJD = GetSubmitOrderParamForJD(shopOrder);
        ReturnSubmitOrderParamForJD returnSubmitOrderParamForJD = JsonConvert.DeserializeObject<ReturnSubmitOrderParamForJD>(DataInteractForJD.GetSubmitOrder(submitOrderParamForJD));
        if (returnSubmitOrderParamForJD.success)
        {
            shopOrder.ExternalNumber = returnSubmitOrderParamForJD.result.jdOrderId;
            shopOrder.OrderNakedPrice = returnSubmitOrderParamForJD.result.orderNakedPrice;
            shopOrder.OrderTaxPrice = returnSubmitOrderParamForJD.result.orderTaxPrice;
            IDAL<Model.EntityModel.Shop_Order> dalShoOrder = new Data.DAL<Model.EntityModel.Shop_Order>();
            dalShoOrder.EditData(shopOrder, "", "ID="+shopOrder.ID);// BLL<Shop_Order>.Creator("UpdateExternalNumber").Parameter(shopOrder);
            return true;
        }
        else
        {
            byte[] myByte = Encoding.UTF8.GetBytes("下单失败，失败原因为:" + returnSubmitOrderParamForJD.resultMessage);
            string strPathLog = strPath + "false" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
            AddLog(myByte, strPathLog);
            return false;
        }
    }
    /// <summary>
    /// 日志工具方法
    /// </summary>
    /// <param name="myByte"></param>
    /// <param name="strPathLog"></param>
    public static void AddLog(byte[] myByte, string strPathLog)
    {
        if (!Directory.Exists(strPath))
        {
            Directory.CreateDirectory(strPath);
        }
        using (FileStream fsWrite = new FileStream(strPathLog, FileMode.Append))
        {
            fsWrite.Write(myByte, 0, myByte.Length);
        };
    }

    /// <summary>
    /// 获取京东下单内容
    /// </summary>
    /// <param name="Shop_Order"></param>
    /// <returns></returns>
    public SubmitOrderParamForJD GetSubmitOrderParamForJD(Shop_Order Shop_Order)
    {
        StringBuilder select_Shop_Order_Goods = new StringBuilder();
        select_Shop_Order_Goods.AppendFormat(" AND Shop_Order_Id = {0}", Shop_Order.ID);
        select_Shop_Order_Goods.Append(" AND Del_Flag = 0");
        IDAL<Model.EntityModel.Shop_Order_Goods> dalShoOrderGood = new Data.DAL<Model.EntityModel.Shop_Order_Goods>();
        List<Shop_Order_Goods> Shop_Order_GoodsList = dalShoOrderGood.Query("select * from View_Shop_Goods WHERE 1=1 AND Del_Flag = 0 AND Shop_Order_Id = "+ Shop_Order.ID);
        //BLL<Shop_Order_Goods>.Creator("SelectView").Parameter(@"*", select_Shop_Order_Goods.ToString());

        SubmitOrderParamForJD submitOrderParamForJD = new SubmitOrderParamForJD();
        submitOrderParamForJD.token = GetJdToken().result.access_token;
        List<Dictionary<string, object>> sku = new List<Dictionary<string, object>>();
        foreach (var item in Shop_Order_GoodsList)
        {
            Dictionary<string, object> goods = new Dictionary<string, object>();
            goods.Add("skuId", item.Number);
            goods.Add("num", item.Quantity);
            goods.Add("bNeedAnnex", true);
            goods.Add("bNeedGift", true);
            goods.Add("price", "");
            //goods.Add("yanbao", "");
            sku.Add(goods);
        }
        submitOrderParamForJD.thirdOrder = Shop_Order.Number;
        submitOrderParamForJD.sku = jss.Serialize(sku);
        submitOrderParamForJD.name = Shop_Order.Consignee_Name;
        submitOrderParamForJD.province = Convert.ToInt32(Shop_Order.Consignee_ProvinceId);
        submitOrderParamForJD.city = Convert.ToInt32(Shop_Order.Consignee_CityId);
        submitOrderParamForJD.county = Convert.ToInt32(Shop_Order.Consignee_CountyId);
        submitOrderParamForJD.town = Convert.ToInt32(Shop_Order.Consignee_CountrysideId);
        submitOrderParamForJD.address = Shop_Order.Consignee_Address;
        submitOrderParamForJD.zip = string.IsNullOrEmpty(Shop_Order.Consignee_ZipCode) ? "" : Shop_Order.Consignee_ZipCode;
        submitOrderParamForJD.phone = "";
        submitOrderParamForJD.mobile = Shop_Order.Consignee_Phone;
        submitOrderParamForJD.email = "wangluobu@zwy365.com";
        submitOrderParamForJD.remark = string.IsNullOrEmpty(Shop_Order.Remark) ? "" : Shop_Order.Remark;
        submitOrderParamForJD.invoiceState = 2;
        submitOrderParamForJD.invoiceType = 2;
        submitOrderParamForJD.selectedInvoiceTitle = 5;
        submitOrderParamForJD.companyName = "债无忧互联网股份有限公司";
        submitOrderParamForJD.invoiceContent = 1;
        submitOrderParamForJD.paymentType = 4;
        submitOrderParamForJD.isUseBalance = 1;
        submitOrderParamForJD.submitState = 1;
        submitOrderParamForJD.invoiceName = "";
        submitOrderParamForJD.invoicePhone = "010-83609511";
        submitOrderParamForJD.invoiceProvice = 1;
        submitOrderParamForJD.invoiceCity = 2805;
        submitOrderParamForJD.invoiceCounty = 2832;
        submitOrderParamForJD.invoiceAddress = "南四环西路128号院2号楼5层506";
        submitOrderParamForJD.doOrderPriceMode = 1;
        List<Dictionary<string, object>> orderPriceSnap = new List<Dictionary<string, object>>();
        foreach (var item in Shop_Order_GoodsList)
        {
            Dictionary<string, object> goods = new Dictionary<string, object>();
            goods.Add("price", item.AgreementPrice);
            goods.Add("skuId", item.Number);
            orderPriceSnap.Add(goods);
        }
        jss.MaxJsonLength = int.MaxValue;
        submitOrderParamForJD.orderPriceSnap = jss.Serialize(orderPriceSnap);
        return submitOrderParamForJD;
    }
}